﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TextGlow.Control.Utilities
{
  public static class StringUtils
  {
    public static string Format(this string format, object arg0)
    {
      return string.Format(format, arg0);
    }

    public static string Format(this string format, params object[] args)
    {
      return string.Format(format, args);
    }

    public static StringBuilder DelimitAppend(this StringBuilder sb, string s)
    {
      if (sb.Length > 0)
        sb.Append(" ");

      return sb.Append(s);
    }

    public static bool ContainsWhiteSpace(string s)
    {
      if (s == null)
        throw new ArgumentNullException("s");

      for (int i = 0; i < s.Length; i++)
      {
        if (char.IsWhiteSpace(s[i]))
          return true;
      }
      return false;
    }

    public static string Reverse(string s)
    {
      if (string.IsNullOrEmpty(s))
        return s;

      char[] characters = s.ToCharArray();
      Array.Reverse(characters);
      return new string(characters);
    }

    public static List<string> SplitOnWhiteSpace(string s, bool removeEmptyEntries)
    {
      if (string.IsNullOrEmpty(s))
        return new List<string>() { s };

      List<string> parts = new List<string>();

      int previousWhiteSpaceEndIndex = 0;
      for (int i = 0; i < s.Length; i++)
      {
        if (char.IsWhiteSpace(s[i]))
        {
          bool partEmpty = ((i - previousWhiteSpaceEndIndex) == 0);

          if (!partEmpty)
          {
            parts.Add(s.Substring(previousWhiteSpaceEndIndex, i - previousWhiteSpaceEndIndex));
            previousWhiteSpaceEndIndex = i + 1;
          }
          else
          {
            if (!removeEmptyEntries)
              parts.Add(string.Empty);

            previousWhiteSpaceEndIndex = i + 1;
          }
        }
      }

      if (previousWhiteSpaceEndIndex < s.Length)
      {
        parts.Add(s.Substring(previousWhiteSpaceEndIndex, s.Length - previousWhiteSpaceEndIndex));
      }

      if (char.IsWhiteSpace(s[s.Length - 1]))
      {
        if (!removeEmptyEntries)
          parts.Add(string.Empty);
      }


      return parts;
    }
  }
}